﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.IO;
using Newtonsoft.Json.Linq;

namespace Util
{
    public class CpuHelper
    {

        public string[] cpuName = new string[5];
        public int[] coreCount = new int[10];
        public int[] ProcessorsCount = new int[10];
        public int cpuCount = 0;
        private static CpuHelper instance;
        protected CpuHelper()
        {
            //Helpers.ConsolePrint(TAG, "QueryCPUs START");
            Helpers.ConsolePrint("CpuHelper", "QueryCPUs START");
            
            // get all CPUs
            foreach (ManagementObject item in new ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                coreCount[cpuCount] = int.Parse(item["NumberOfCores"].ToString());
                
                cpuName[cpuCount] = item["Name"].ToString();
                cpuCount++;
            }
            int i = 0;
            foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
            {
                
                ProcessorsCount[i] = int.Parse(item["NumberOfLogicalProcessors"].ToString());
                i++;
            }

            Helpers.ConsolePrint("CpuHelper", "QueryCPUs END");
            
            //Helpers.ConsolePrint(TAG, "QueryCPUs END");
        }

        public static CpuHelper GetInstance()
        {
            if (instance == null)
            {
                instance = new CpuHelper();
            }
            return instance;
        }

        public string WriteJsonFile(object config, string filename)
        {
            var header = "// This config file was autogenerated by NHML.";

            try
            {
                var confJson = JObject.FromObject(config);
                var writeStr = confJson.ToString();
                var start = writeStr.IndexOf("{");
                var end = writeStr.LastIndexOf("}");
                writeStr = writeStr.Substring(start + 1, end - 1);
                writeStr = header + "\n" + writeStr;
                File.WriteAllText(filename, writeStr);
            }
            catch (Exception e)
            {
                Helpers.ConsolePrint("CpuHelper", e.ToString());
                Helpers.ConsolePrint("CpuHelper", $"Config {filename} was unable to write for xmr-stak, mining may not work");
            }

            return filename;
        }

    }
}
